package com.reny.szkj.ft_home.ui.index.home

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.reny.ll.git.base_logic.MViewModel
import com.reny.ll.git.base_logic.api.exceptionProcess
import com.reny.ll.git.base_logic.api.process
import com.reny.ll.git.base_logic.config.pageSize
import com.reny.ll.git.base_logic.ext.isEmpty
import com.reny.ll.git.base_logic.model.reny.GirlBean
import com.reny.ll.git.mvvm.state.STATE_CONTENT
import com.reny.ll.git.mvvm.state.STATE_EMPTY

class HomeViewModel(private val repo: HomeRepository) : MViewModel() {

    private var page = 1

    val liveResult: MutableLiveData<List<GirlBean>> = MutableLiveData()

    override fun loadData(refresh: Boolean) {
        super.loadData(refresh)

        launch(exceptionProcess()) {
            var p = if (refresh) 1 else page
            val result = repo.api.getGirls(p).process()
            page = ++p

            val noMore = result?.size ?: 0 < pageSize
            setLoadState(if(isEmpty(result)) STATE_EMPTY else STATE_CONTENT, noMore, refresh)

            liveResult.postValue(result)
        }
    }

}


@Suppress("UNCHECKED_CAST")
class LoginViewModelFactory(
    private val repo: HomeRepository
) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T = HomeViewModel(repo) as T

}